const { polylineToGeoJson } = require("./geo/index");
const { reqByKeywords } = require("./request/index");
const { poolQuery, insert, pool, selectByLevel, insertWithoutGeom, updataGeomById } = require("./pg/query");

async function doItem(item) {
  const { polyline, districts } = await reqByKeywords(item.adcode);
  const geojson = JSON.stringify(polylineToGeoJson(polyline));
  await updataGeomById(geojson, item.id);
  console.log(`更新行政区${item.name}信息成功,准备入库下属行政区`);

  for (let v of districts) {
    const { citycode, adcode, name, center, level } = v;
    await insertWithoutGeom(citycode, adcode, name, center, level, item.id);
  }
  console.log(`行政区${item.name}的下属行政区入库完成`);
}

(async function main() {
  //单独入库country
  const { citycode, adcode, name, center, level, polyline } = await reqByKeywords("中国");
  const geojson = JSON.stringify(polylineToGeoJson(polyline));
  await insert(citycode, adcode, name, geojson, center, level, -1);
  //每次更改不同的level
  for (let lvl of ["country", "province", "city", "district"]) {
    const { rows } = await selectByLevel(lvl);
    for (let item of rows) {
      await doItem(item);
    }
  }

  pool.end((e) => console.log("操作结束"));
})();
